# -*- coding: utf-8 -*-
"""
"""

from sqlalchemy import *
from sqlalchemy.orm import mapper, relation
from sqlalchemy import Table, ForeignKey, Column
from sqlalchemy.types import Integer, Unicode

from abserver.model import DeclarativeBase, metadata, DBSession


# This is the association table for the many-to-many relationship between
# BuildBlessing and BuildView.
buildblessing_buildviews_table = Table('buildblessing_buildview_mm', metadata,
                                       Column('blessing_level', Integer, ForeignKey('buildblessing.blessing_level',
                                                                                    onupdate="CASCADE", ondelete="CASCADE")),
                                       Column('buildview_id', Integer, ForeignKey('buildview.buildview_id',
                                                                                  onupdate="CASCADE", ondelete="CASCADE"))
                               )

class BuildBlessing(DeclarativeBase):
    """This entity describes a blessing level. These are currently hard-wired, but
    there's nothing in principle about these being more configurable.
    """
    # table options
    __tablename__ = 'buildblessing'

    # columns
    blessing_level = Column(Integer, primary_key=True, autoincrement=True)
    blessing_name = Column(Unicode(64), nullable=False, unique=True)
    blessing_description = Column(Unicode(), nullable=True)

    # relationships
    ## blessed_tasks
    buildviews = relation('BuildView', secondary=buildblessing_buildviews_table, backref='buildblessings')

#    def __init__(self, blessing_name, blessing_description):
#        self.blessing_name = blessing_name
#        self.blessing_description = blessing_description

    @classmethod
    def get(cls, level):
        bless = DBSession.query(cls).filter(cls.blessing_level==level).one()
        return bless

    @classmethod
    def get_blessing(cls, name, description):
        """Convenience getter or factory method."""
        bless = DBSession.query(cls).filter(cls.blessing_name==name).first()
        if not bless:
            bless = BuildBlessing(blessing_name=name, blessing_description=description)
            DBSession.add(bless)
        return bless

    @classmethod
    def get_unblessed(cls):
        return cls.get_blessing('Unblessed', 'This bless level describes a build which has been made, and is a candidate for automatic deletion after some time')

    @classmethod
    def get_blessing_list(cls):
        blessings = DBSession.query(cls).all()
        return [ (b.blessing_level, b.blessing_name) for b in blessings ]

    def blessed(self):
        return self.blessing_level > 1

